﻿using BLL.RYGL;
using Models;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace YQFK.Controllers
{
    public class HomeController : Controller
    {
        private readonly EmployeeBLL _employeeBLL;

        public HomeController()
        {
            _employeeBLL = new EmployeeBLL();
        }

        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }

        public async Task<ActionResult> Upload(string deptid)
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> Upload(string id, HttpPostedFileBase postfile)
        {
            NLog.LogManager.GetCurrentClassLogger().Debug("开始导入");
            if (postfile == null)
            {
                ModelState.AddModelError(string.Empty, "请选择导入文件！");
                NLog.LogManager.GetCurrentClassLogger().Debug("文件验证不通过");
                return View();
            }

            IWorkbook workbook;
            try
            {
                workbook = new XSSFWorkbook(postfile.InputStream);
            }
            catch (Exception)
            {
                ModelState.AddModelError(string.Empty, "文件异常，请选择导入文件！");
                NLog.LogManager.GetCurrentClassLogger().Debug("文件流验证不通过");
                return View();
            }

            ISheet sheet = workbook.GetSheetAt(0);
            var models = new List<EmployeeModel>();
            for (int i = 1; i <= sheet.LastRowNum; i++)
            {
                var model = new EmployeeModel();
                var row = sheet.GetRow(i);
                model.DisplayName = row.GetCell(0).StringCellValue;
                model.Gender = row.GetCell(1).StringCellValue;
                model.Age = (int)row.GetCell(2).NumericCellValue;
                model.PhoneNumber = row.GetCell(3).StringCellValue;
                model.IdentityNumber = row.GetCell(4).StringCellValue;
                model.EmployeeType = row.GetCell(5)?.StringCellValue;
                model.ReworkDate = DateTime.Now;
                model.EmployeeStatus = "已进场";
                model.EmployeeId = Guid.NewGuid();
                model.CreateTime = DateTime.Now;
                model.DepartmentId = id;
                models.Add(model);
            }

            NLog.LogManager.GetCurrentClassLogger().Debug("数据验证开始");

            var phoneExp = new Regex(@"(^0\d{2,3}\-\d{7,8}$)|(^1[3|4|5|6|7|8][0-9]{9}$)");
            var idExp = new Regex(@"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)");
            var allValid = true;
            for (int i = 0; i < models.Count; i++)
            {
                var model = models[i];
                if (!phoneExp.IsMatch(model.PhoneNumber))
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}联系电话不正确！");
                    allValid = false;
                }
                if (!idExp.IsMatch(model.IdentityNumber))
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}身份证号不正确！");
                    allValid = false;
                }
                if (string.IsNullOrEmpty(model.EmployeeType))
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}请选择人员类型！");
                    allValid = false;
                }
                if (models.Count(x => x.EmployeeId != model.EmployeeId && x.DisplayName == model.DisplayName) > 0)
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}姓名在表中已存在！");
                    allValid = false;
                }
                if (models.Count(x => x.EmployeeId != model.EmployeeId && x.PhoneNumber == model.PhoneNumber) > 0)
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}联系电话在表中已存在！");
                    allValid = false;
                }
                if (models.Count(x => x.EmployeeId != model.EmployeeId && x.IdentityNumber == model.IdentityNumber) > 0)
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}身份证号在表中已存在！");
                    allValid = false;
                }
                if (await _employeeBLL.Exists(model.DepartmentId, model.IdentityNumber))
                {
                    ModelState.AddModelError(string.Empty, $"行{i + 2}身份证号已存在！");
                    allValid = false;
                }
            }
            NLog.LogManager.GetCurrentClassLogger().Debug("数据验证完成");

            if (allValid)
            {
                NLog.LogManager.GetCurrentClassLogger().Debug("数据插入开始");
                _employeeBLL.CreateAsync(models, id);
                NLog.LogManager.GetCurrentClassLogger().Debug("导入完成");
            }

            NLog.LogManager.GetCurrentClassLogger().Debug("数据验证不通过");

            return View();
        }
    }
}
